# -*- coding:utf-8 -*-

from enum import Enum
from pydantic import BaseModel
from collections import namedtuple
from fastapi import Depends, Request

from core.exceptions import ServiceException

from utils.dependence import PageFilter

class BaseService:
    async def pages(self, page_no: int=1, page_size: int=10, page_filter: PageFilter=None):
        return await self.dao.pages(page_no, page_size, page_filter)
    
    async def get_by_id(self, id: int):
        return await self.dao.get_by_id(id)

    async def first(self, filter: BaseModel):
        return await self.dao.first(filter)

    async def create(self, request: Request, data: BaseModel):
        filter, in_, like, order_by= self.dao.filter(PageFilter(None, {'name': data.name}, None, None))
        count = await self.dao.count(filter=filter)
        if count > 0:
            raise ServiceException(code=409, message=f"已存在")
        create_user = self.get_current_user(request).id
        # 封装
        data = self.SCHEMA(**data, create_user=create_user)
        data_db = await self.dao.add(data)
        return data_db

    async def delete(self, request: Request, id: int):
        data_db = await self.dao.get_by_id(id)
        if not data_db:
            raise ServiceException(code=404, message=f"用户不存在")
        update_user = self.get_current_user(request).id
        data = self.SCHEMA.from_orm(data_db).dict()
        data['update_user'] = update_user
        data['del_flag'] = 1
        return await self.dao.update(id, data)

    async def update(self, request: Request, id: int, data: BaseModel):
        data_db = await self.dao.get_by_id(id)
        if not data_db:
            raise ServiceException(code=404, message=f"用户不存在")
        update_user = self.get_current_user(request).id
        data = {key: val.value if isinstance(val, Enum) else val for key, val in data.dict().items()}
        data['update_user'] = update_user
        return await self.dao.update(id, data)

    def get_current_user(self, request: Request):
        if hasattr(request.state, 'user'):
            return request.state.user
        return namedtuple("User", ["id", "name"])(-1, '匿名用户')

